#define QT_NO_DEBUG_OUTPUT
#include "spot.h"
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>

Spot::Spot(QWidget *parent) : QWidget(parent)
{
    _radius = 10;
    setradius(_radius);

    _f_setpainter = [](QPainter& painter){
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setPen(QPen(Qt::red, 3));
        painter.setBrush(Qt::NoBrush);
    };
}

Spot::~Spot(){}

void Spot::mousePressEvent(QMouseEvent *event)
{
    if(!_mousepressed && event->button() == Qt::LeftButton){
        _mousepressed = true;
        qDebug() << "mouse clicked at : " << event->pos();
        qDebug() << "spot pos : " << pos();
        _oldmousepos = event->pos();
        _oldpos = pos();
        if(_oldmousepos.x() > radius() * 2){
            _mousepressed = false;
            event->ignore();
            return;
        }
    }

    QWidget::mousePressEvent(event);
}

void Spot::mouseReleaseEvent(QMouseEvent *event)
{
    _mousepressed = false;
    QWidget::mouseReleaseEvent(event);
}

void Spot::mouseMoveEvent(QMouseEvent *event)
{
    if(_mousepressed){
        qDebug() << "mouse move to : " << event->globalPos() << event->pos();

        // event->pos() - _oldmousepos 就是需要调整的距离
        QPoint dst = pos() + (event->pos() - _oldmousepos);
        // 这里拆开写,方便以后添加位置检查
        move(dst);
    }
    QWidget::mouseMoveEvent(event);
}

void Spot::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    _f_setpainter(painter);

    int r = radius();
    painter.drawEllipse(QPoint(r, r), r - 3, r - 3);
}

void Spot::dragable(bool candrag)
{
    setAttribute(Qt::WA_TransparentForMouseEvents, candrag);
}

void Spot::focusout()
{
    _mousepressed = false;
}

QPoint Spot::getpos() const
{
    QPoint ret = geometry().center();
    qDebug() << "pos : " << ret;
    return ret;
}

const QRect &Spot::getrect() const
{
    return geometry();
}

int Spot::radius() const
{
    return _radius;
}

void Spot::setpos(const QPoint &pos)
{
    int r = radius();
    QPoint dst(pos.x() - r, pos.y() - r);
    qDebug() << "dst : " << dst;
    move(dst);
}

void Spot::setradius(int r)
{
    _radius = r;
    QPoint left_up = getpos() - QPoint(r, r);
    qDebug() << "left_up : " << left_up;
    int d = r * 2;
    setGeometry(left_up.x(), left_up.y(), d, d);
}
